﻿using System.Collections.Specialized;
using System.Web;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Workflow.Runtime.Tracking;
using PD.DataAccess.Properties;
using PD.WorkflowLibrary;

namespace PD.Web
{
    /// <summary>
    /// Represents the configurable execution environment provided by the workflow run-time engine for workflows.
    /// </summary>
    internal sealed class PDWorkflowRuntimeUtility
    {
        /// <summary>
        /// Prevents a default instance of the <see cref="PDWorkflowRuntimeUtility"/> class from being created.
        /// </summary>
        private PDWorkflowRuntimeUtility()
        {
        }

        /// <summary>
        /// Gets the current workflow runtime.
        /// </summary>
        public static WorkflowRuntime CurrentWorkflowRuntime
        {
            get
            {
                HttpContext context = HttpContext.Current;
                WorkflowRuntime workflowRuntime = null;
                context.Application.Lock();
                workflowRuntime = context.Application[PDConstants.WorkflowRuntimeInstanceKey] as WorkflowRuntime;
                context.Application.UnLock();
                if (workflowRuntime == null)
                {
                    workflowRuntime = PDWorkflowRuntimeUtility.Configure();
                    context.Application.Lock();
                    context.Application[PDConstants.WorkflowRuntimeInstanceKey] = workflowRuntime;
                    context.Application.UnLock();
                }

                return workflowRuntime;
            }
        }

        /// <summary>
        /// Configures this instance.
        /// </summary>
        /// <returns>
        /// The current workflow runtime.
        /// </returns>
        public static WorkflowRuntime Configure()
        {
            WorkflowRuntime workflowRuntime = new WorkflowRuntime();

            NameValueCollection parameters = new NameValueCollection();
            parameters.Add("ConnectionString", Settings.Default.PDConnectionString);
            parameters.Add("UnloadOnIdle", "true");

            workflowRuntime.AddService(new SqlWorkflowPersistenceService(parameters));
            workflowRuntime.AddService(new SqlTrackingService(Settings.Default.PDConnectionString));
            workflowRuntime.AddService(new ManualWorkflowSchedulerService());

            ExternalDataExchangeService dataService = new ExternalDataExchangeService();
            workflowRuntime.AddService(dataService);
            dataService.AddService(new InvoiceProcessingService());

            workflowRuntime.AddService(new SharedConnectionWorkflowCommitWorkBatchService(Settings.Default.PDConnectionString));
            workflowRuntime.StartRuntime();

            return workflowRuntime;
        }
    }
}